package itdep.common.context.spring;

import org.drools.KnowledgeBase;
import org.drools.runtime.StatefulKnowledgeSession;
import org.springframework.security.acls.model.Acl;
import org.springframework.security.acls.model.NotFoundException;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.acls.model.Sid;

import java.util.List;

/**
 * @author $Author: ikhalopik $ (latest modification by $Author: ikhalopik $:)
 * @version $Revision: 4 $   $Date: 2010-06-10 13:13:16 +0000 (Thu, 10 Jun 2010) $
 */
public class DroolsSecurityChecker implements SecurityChecker {
	private final KnowledgeBase knowledgeBase;

	public DroolsSecurityChecker(final KnowledgeBase knowledgeBase) {
		this.knowledgeBase = knowledgeBase;
	}

	public boolean check(final Acl acl, final List<Sid> sids, final List<Permission> permissions) {
		for (Sid sid : sids) {
			if (check(acl, sid, permissions)) {
				return true;
			}
		}
		return false;
	}

	private boolean check(final Acl acl, final Sid sid, final List<Permission> permissions) {
		for (Permission permission : permissions) {
			if (check(acl, sid, permission)) {
				return true;
			}
		}
		return false;
	}

	private boolean check(final Acl acl, final Sid sid, final Permission permission) throws NotFoundException {
		final StatefulKnowledgeSession knowledgeSession = knowledgeBase.newStatefulKnowledgeSession();
		final DynamicAce ace = new DynamicAce(acl, permission, sid);
		knowledgeSession.insert(ace);
		knowledgeSession.fireAllRules();
		return ace.isGranting();
	}
}
